package com.gdc.cloud.controller;

import com.gdc.cloud.entities.CommonResult;
import com.gdc.cloud.entities.Payment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * Description: 订单消费者模块启动类
 * @author: gdc
 * @date: 2021/1/31
 * @version 1.0
 */
@RestController
@Slf4j
public class OrderController {

    public static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";

    @Resource
    private RestTemplate restTemplate;
    @Resource
    private DiscoveryClient discoveryClient;

    /**
     * 注入自定义负载均衡接口
     */
    //@Resource
    //private LoadBanlancer loadBanlancer;

    /**
     * 创建 支付信息
     * @param payment               支付信息
     * @return                      结果
     */
    @GetMapping("/consumer/payment/create")
    public CommonResult<Payment> create(Payment payment){
        return restTemplate.postForObject(PAYMENT_URL+"/payment/create" ,payment, CommonResult.class);
    }

    /**
     * 通过ID获取支付信息
     * @param id                    ID
     * @return                      支付信息
     */
    @GetMapping("/consumer/payment/get/{id}")
    public CommonResult<Payment> getPayment(@PathVariable("id") Long id) {
        return restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);
    }

    /**
     * 通过自定义 负载均衡类 来测试获取获取数据
     * @return                      结果
     */
    /*@GetMapping("/consumer/payment/lb")
    public String lb(){
        // 获取所有服务实例
        List<ServiceInstance> serviceInstances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        if (CollectionUtils.isEmpty(serviceInstances)) {
            return null;
        }

        // 通过自定义算法，获取可用服务实例进行请求
        ServiceInstance instance = loadBanlancer.instance(serviceInstances);
        URI uri = instance.getUri();
        return restTemplate.getForObject(uri + "/payment/lb", String.class);
    }*/

    /**
     * 测试 链路追踪接口
     * @return                      结果
     */
    @GetMapping(value="/consumer/payment/zipkin")
    public String paymentZipkin() {
        return restTemplate.getForObject(PAYMENT_URL + "/payment/zipkin/",String.class);
    }
}
